const express = require('express');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const userService = require('../services/userService');


var router = express.Router();

// 注册
router.post('/register', async function (req, res) {
    var req = req.body;
    // console.log(req);
    if (req.name == '' || req.name == undefined) {
        res.send({
            success: false,
            msg: '用户名不能为空！'
        })
    } else {
        var data = await userService.addUser(req);
        // console.log(data);
        res.send(data);
    }
})

router.post('/login', async function (req, res, next) {
    var user = req.body;
    if (user.name == '' || user.name == undefined) {
        res.send({
            success: false,
            msg: '用户名不能为空！'
        })
    } else {
        var data = await userService.login(user);
        // res.send(data);
        if (data.success) {
            // 判断用户是否要记住登录信息,以便一定时间内自动登录
            // 注意：checked得到的值是string类型的
            // console.log(req.remember,typeof req.remember);     true string
            // 设置管理员不可记住信息在cookies中，故管理员不能有自动登录
            req.session.user = data.user;  // 将用户信息记录session
            if (data.user.role === 'user') {
                if (user.remember === 'true') {
                    res.cookie('user', data.user, { maxAge: 24*60 * 60 * 1000 });
                }
                res.send(data);
            } else if (data.user.role == 'admin') {
                res.send({ role: 'admin',url: '/views/admin/admin.html'})
                // res.redirect('/views/admin/admin.htmvl');        ajax提交不可用res.redirect()转发页面
            }
        } else {
            res.send(data);
        }
    }
})

// 用户退出登录，清除session
router.use('/logOut', function (req, res) {
    // console.log(req.session['user']);  //此前session存放当前用户信息
    req.session['user'] = '';
    res.clearCookie('user');
    // console.log(typeof req.session.user);                 //string
    // console.log(req.session.user==='')                    //true
    res.redirect('/');
})



exports.router = router;